package cn.bdqn.sms.system.controller;

import cn.bdqn.sms.common.R.R;
import cn.bdqn.sms.common.dto.LoginDTO;
import cn.bdqn.sms.system.entity.SysMenu;
import cn.bdqn.sms.system.service.SysMenuService;
import cn.bdqn.sms.system.service.SysUserService;
import cn.bdqn.sms.system.vo.SysUserVO;
import cn.dev33.satoken.stp.StpUtil;
    import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @author zhangpengxiang
 * @description 登录控制器
 * @date 2024/11/19
 */
@RestController
public class LoginController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysMenuService sysMenuService;

    @PostMapping("/login")
    public R login(@Valid @RequestBody LoginDTO loginDTO){
        // 调用用户服务进行登录验证并获取用户视图对象
        SysUserVO user = sysUserService.login(loginDTO);

        // 若用户为null，即用户名或密码错误，返回相应错误信息及状态码
        if (user == null) {
            return R.failure("用户名或密码错误！");
        }

        //登录并创建会话
        StpUtil.login(user.getUserId());
        user.setToken(StpUtil.getTokenValue());
        StpUtil.getSession().set("user",user);

        //登录成功返回用户信息
        return R.success(user);
    }

    @GetMapping("/getRoutes")
    public List<SysMenu> getRouters(Long userId){
        List<SysMenu> menuList = sysMenuService.selectMenuTreeByUserId(userId);
        return menuList;
    }
}
